const { v4 } = require("uuid");
const { Result } = require("@/libs/result");
const arrayUtil = require("@/utils/array.util");
const dateUtil = require("@/utils/date.util");
const dbTableNameConstant = require("@/constants/db-table-name.constant");
const CommonService = require("@/common/common.service");
const tableModel = require("./table.model");
const fileBusinessService = require("@/common/file-business.service");

/**
 * 产品服务
 * @author Haor
 * @created 2025/2/18
 */
class TableService {
    commonService = new CommonService();
    async queryTableList({ keyword } = {}) {
        try {
            console.log(keyword);
            const results = await tableModel.queryTableList({ keyword: keyword || '' });
            if (results.code !== 200) {
                return Result.Failed('查询失败')
            }
            return Result.Success(results.results);
        } catch (error) {
            console.log("查询桌台列表失败：", error);
            return Result.Failed('查询失败')
        }
    }

    /**
     * 创建桌台
     * @param {*} body
     * @returns
     */
    async createTable(data, { tid, user }) {
        try {
            const [_createError, createResult] = await tableModel.createTable({
                area_id: data.area_id,
                table_code: data.table_code,
                table_name: data.table_name,
                table_type: data.table_type,
                capacity: data.capacity
            });
            if (_createError) {
                return Result.Failed("创建桌台失败");
            }
            return Result.Success(createResult);
        } catch (error) {
            console.log("创建桌台失败：", error);
            return Result.Failed(error);
        }
    }

    /**
     * 创建区域
     * @param {*} data
     * @returns
     */
    async createArea(data) {
        try {
            const [_createError, createResult] = await tableModel.createTableArea({
                shop_id: data.shop_id,
                area_code: data.area_code,
                area_name: data.area_name,
                floor: data.floor,
                area_type: data.area_type,
                capacity: data.capacity,
                feature_tags: data.feature_tags ? JSON.stringify(data.feature_tags) : ""
            });
            if (_createError) {
                return Result.Failed("创建失败");
            }
            return Result.Success(createResult);
        } catch (error) {
            console.log("创建失败：", error);
            return Result.Failed(error);
        }
    }
    
    /**
     * 查询区域
     * @param {*} data
     * @returns
     */
    async queryTableAreaList(data) {
        try {
            const result = await tableModel.queryTableAreaList();
            if (result.code !== 200) {
                return Result.Failed("查询失败");
            }
            // 特色标签JSON序列化一下
            let areaList = Array.isArray(result.results) ? result.results.map(row => {
                return {
                    ...row,
                    feature_tags: row.feature_tags ? JSON.parse(row.feature_tags) : null
                }
            }) : [];
            // 排序
            areaList = areaList.sort((a, b) => a.sort_order - b.sort_order);
            return Result.Success(areaList);
        } catch (error) {
            console.log("查询失败", error);
            return Result.Failed(error);
        }
    }

    async createBillingRule(data) {
        try {
            if (!data.rule_type) {
                return Result.Failed("创建规则失败");
            }
            const ruleType = data.rule_type || 1;
            const billingRuleParams = this._getBillingRuleParams(ruleType, data);
            const ruleParams = {
                rule_name: data.rule_name || "",
                rule_type: ruleType,
                ...billingRuleParams, // 根据规则获取动态字段
                /*********** 公共字段 **************/
                // 优先级
                priority: data.priority || 0,
                // 适用星期
                weekdays: data.weekdays,
                // 过期日期
                effective_date: data.effective_date,
                // 失效日期
                expire_date: data.expire_date,
                // 描述
                description: data.description,

                /*********** 超时字段 **************/
                // 超时费率
                overtime_rate: data.overtime_rate,
                // 是否启用超时计费
                overtime_enabled: data.overtime_enabled,
                // 超时费用/单位
                overtime_fee: data.overtime_fee,
                // 超时计费单位：1-分钟 2-小时
                overtime_unit: data.overtime_unit,
                // 超时舍入方式：1-向上取整 2-向下取整 3-四舍五入
                overtime_rounding: data.overtime_rounding,
                // 最大超时时长(0表示不限制)
                max_overtime: data.max_overtime,
                // 超时费率
                overtime_rate: data.overtime_rate,
            };
            const [createError, result] = await tableModel.createRule(ruleParams);
            if (createError) {
                return Result.Failed("创建规则失败");
            }
            return Result.Success(result);
        } catch (error) {
            console.log("创建失败：", error);
            return Result.Failed("创建规则失败");
        }
    }

    /**
     * 设置桌台规则
     * @param {*} table_id 
     * @param {*} data 
     */
    async setTableRule({ table_id }, data) {
        try {
            const params = data.rules.map(id => {
                return {
                    shop_id: data.shop_id,
                    table_id: table_id,
                    rule_id: id
                }
            });
            const [error, results] = await tableModel.bindTableRules(params);
            if (error) {
                return Result.Failed('设置桌台规则失败');
            }
            return Result.Success(results);
        } catch (error) {
            console.log('设置桌台规则失败：', error.message);
            return Result.Failed('设置桌台规则失败');
        }
    }

    /**
     * 获取桌台规则
     * @param {*} param0 
     * @returns 
     */
    async getTableRule({ table_id }) {
        try {
            console.log(table_id);
            const result = await tableModel.getTableRule({ table_id: table_id });
            if (result.code === 200) {
                const rules = result.results;
                const ruleList = rules.sort((a, b) => a.priority - b.priority);
                return Result.Success(ruleList);   
            }
            return Result.Failed('获取规则失败');
        } catch (error) {
            console.log('查询桌台规则失败：', error.message);
            return Result.Failed('获取规则失败');
        }
    }

    /**
     * 查询桌台状态数量
     * @returns 
     */
    async getTableStatusQuantity() {
        try {
            const result = await tableModel.getStatusQuantity();
            if (result.code !== 200) {
                return Result.Failed('查询失败') 
            }
            return Result.Success(result.results);
        } catch (error) {
            console.log('查询状态数量失败：', error);
            return Result.Failed('查询失败')
        }
    }

	/**
	 * 获取计费规则参数
	 * @param {*} ruleType
	 * @param {*} data
	 */
	_getBillingRuleParams(ruleType, data) {
        // 固定时段计费
		if (ruleType === 1) {
			return {
				start_time: data.start_time,
				end_time: data.end_time,
				fixed_fee: data.fixed_fee || 0,
				fixed_duration: data.fixed_duration || 0
			};
		}
		// 小时计费
		if (ruleType === 2) {
			return {
				base_hours: data.base_hours || 0, // 最低消费时长
				hourly_rate: data.hourly_rate || 0, // 每小时费率
				base_fee: data.base_fee || 0 // 基础费用
			};
		}
        // 分段计费
        if (ruleType === 3) {
            return {
                segment_json: data.segment_json ? JSON.stringify(data.segment_json) : "",
            }
        }
        // 包场
        if (ruleType === 4) {
            return {
                fixed_duration: data.fixed_duration, // 固定时长(小时)
                fixed_price: data.fixed_price || 0, // 固定价格'
                start_time: data.start_time,
                end_time: data.end_time
            }
        }
	}
}

module.exports = new TableService();
